package cn.wzy.service.impl;

import cn.wzy.dto.LoginDTO;
import cn.wzy.enums.AppHttpCodeEnum;
import cn.wzy.mapper.EmployeeMapper;
import cn.wzy.pojo.Employee;
import cn.wzy.results.ResponseResult;
import cn.wzy.service.LoginService;
import cn.wzy.utils.RedisCache;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.UUID;

@Service
public class LoginServiceImpl implements LoginService {


    @Resource
    private EmployeeMapper employeeMapper;

    @Resource
    private RedisCache redisCache;
    /*
    * 登入
    * */
    @Override
    public ResponseResult login(LoginDTO loginDTO) {
//        数据校验
        if (StringUtils.isEmpty(loginDTO.getUsername())){
            return ResponseResult.errorResult(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
//        判断是否有该用户
        Employee employee = employeeMapper.getEmployeeByUsername(loginDTO.getUsername());
        if (Objects.isNull(employee)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR);
        }
//        判断密码是否正确
        if (!employee.getPassword().equals(loginDTO.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR);
        }
//        生成一个随机树作为id
        String token = UUID.randomUUID().toString().replaceAll("-", "");
//        保存到rides
        redisCache.setCacheObject("User:"+token,employee);
//        返回token
        return ResponseResult.okResult(token);
    }

    /*
    * 退出登入
    * */
    @Override
    public ResponseResult loginOut(HttpServletRequest request) {
        String token = request.getHeader("token");
        redisCache.deleteObject("User:"+token);
        return ResponseResult.okResult();
    }
}
